﻿using System.IO;
using System.Web;

namespace XWeb.Web.Sass.Handlers
{
    public class SassHttpHandler: IHttpHandler
    {
		private class SassSourceProvider : ISourceProvider
		{
			private readonly HttpContext _httpContext;
			public string Path { get; private set; }

			private string _content;
			public string Content
			{
				get { return _content ?? (_content = File.ReadAllText(_httpContext.Server.MapPath(Path))); }
			}

			public ISourceProvider Resolve(string path)
			{
				var dir = VirtualPathUtility.GetDirectory(Path);
				var newPath = VirtualPathUtility.Combine(dir, path);
				return new SassSourceProvider(_httpContext, newPath);
			}

			public SassSourceProvider(HttpContext httpContext, string path)
			{
				_httpContext = httpContext;
				Path = path;
			}
		}

    	/// <summary>
    	/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
    	/// </summary>
    	/// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param>
    	public void ProcessRequest(HttpContext context)
    	{
			context.Response.Write(SassCompiler.CompileSource(new SassSourceProvider(context, "~" + context.Request.Path), OutputStyle.Nested));
    		context.Response.ContentType = "text/css";
    	}

    	/// <summary>
    	/// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
    	/// </summary>
    	/// <returns>
    	/// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
    	/// </returns>
    	public bool IsReusable
    	{
    		get { return true; }
    	}
    }
}
